﻿@model SmartAdmin.WebUI.ViewComponents.ImportExcelOptions

<div class="modal fade" id="fileupload" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-sm" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="ModalLabel">Excel上传导入</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body p-0">
        <input type="file" multiple="multiple" name="uploadfiles" id="uploadfiles">
      </div>
    </div>
  </div>
</div>
<script type="text/javascript">
    var importExcel = {
      //上传导入附件
      upload: function () {
        $('#fileupload').modal('toggle');
      },
      //下载Excel导入模板
      downloadtemplate: function () {
        const url = '@(Model.url)/Download?file=ExcelTemplate\\@(Model.tpl)';
        $.fileDownload(url)
          .done(() => {
            toastr.success('模板下载完成!');
          })
          .fail(() => {
            $.messager.alert('错误', '没有下载到导入模板[@(Model.tpl)]文件!', 'error');
          });
      },
      init: function () {
        $('input[name="uploadfiles"]').fileuploader({
          limit: 1,
          maxSize: 20,
          fileMaxSize: 20,
          captions: {
            feedback: 'Drag and drop files here',
            feedback2: 'Drag and drop files here',
            drop: 'Drag and drop files here',
            or: 'or',
            button: 'Browse files'
          },
          changeInput: '<div class="fileuploader-input">' +
            '<div class="fileuploader-input-inner">' +
            '<div class="fileuploader-main-icon"></div>' +
            '<h3 class="fileuploader-input-caption"><span>Drag and drop files here</span></h3>' +
            '<p>or</p>' +
            '<div class="fileuploader-input-button js-waves-on"><span>Browse files</span></div>' +
            '</div>' +
            '</div>',
          theme: 'dragdrop',
          extensions: ['xlsx', 'xls', 'csv'],
          upload: {
            url: "@(Model.url)/ImportExcel",
            data: {
              autosave:@Json.Serialize(Model.autosave),
              model: '@Model.entity',
              folder: '@Model.folder',
              @if (Model.properties != null) {
                 @:properties: JSON.parse('@Html.Raw(Json.Serialize(Model.properties))')
              }
              },
            type: 'POST',
            enctype: 'multipart/form-data',
            start: true,
            synchron: false,
            beforeSend: function (item) {

            },
            onSuccess: function (result, item) {
              //console.log(result,item)
              // if success
              if (result.success ) {
                //item.name = item.name;
                item.html.find('.column-title > div:first-child').text(item.name).attr('title', item.name);
                $.messager.alert('完成导入', `导入 ${result.total} 行 耗时：${result.elapsedTime}`,'info');
                reload();
                $('#fileupload').modal('toggle');
              } else {
                item.html.find('.column-title > div:first-child').text(item.name).attr('title', item.name);
                item.html.removeClass('upload-successful').addClass('upload-failed');
                // go out from success function by calling onError function
                // in this case we have a animation there
                // you can also response in PHP with 404
                //alert(result.message);
                $.messager.alert('导入失败', result.err , 'error');
                return this.onError ? this.onError(item) : null;

              }



              item.html.find('.fileuploader-action-remove').addClass('fileuploader-action-success');
              setTimeout(function () {
                item.html.find('.progress-bar2').fadeOut(400);
              }, 400);
            },
            onError: function (item) {
              var progressBar = item.html.find('.progress-bar2');

              if (progressBar.length) {
                progressBar.find('span').html(0 + "%");
                progressBar.find('.fileuploader-progressbar .bar').width(0 + "%");
                item.html.find('.progress-bar2').fadeOut(400);
              }

              item.upload.status != 'cancelled' && item.html.find('.fileuploader-action-retry').length == 0 ? item.html.find('.column-actions').prepend(
                '<a class="fileuploader-action fileuploader-action-retry" title="Retry"><i></i></a>'
              ) : null;
            },
            onProgress: function (data, item) {
              var progressBar = item.html.find('.progress-bar2');

              if (progressBar.length > 0) {
                progressBar.show();
                progressBar.find('span').html(data.percentage + "%");
                progressBar.find('.fileuploader-progressbar .bar').width(data.percentage + "%");
              }
            },
            onComplete: null
          },
          onRemove: function (item) {

            var filename = item.html.find('.column-title > div:first-child').attr('title');
            $.post('/FileUpload/Remove', { filename: filename });

          },
          thumbnails: {
            canvasImage: false,
            popup: null
          }
        });
      }
    };
    document.addEventListener("DOMContentLoaded", function () {
      $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/js/plugin/jquery.fileuploader/jquery.fileuploader.min.css'));
      $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/js/plugin/jquery.fileuploader/jquery.fileuploader-theme-dragdrop.css'));
      $('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', '/js/plugin/jquery.fileuploader/font/font-fileuploader.css'));
      $.when($.getScript('/js/plugin/filesaver/jquery.fileDownload.js'),
        $.getScript('/js/plugin/jquery.fileuploader/jquery.fileuploader.min.js')
      ).done(function() {
        importExcel.init();
      });



    });

</script>
